package com.apes.fn.scm.internal.help.service;

import com.apes.fn.scm.internal.help.model.InternalHelpReturnApproval;
import com.apes.fn.scm.internal.help.model.InternalHelpReturnApprovalItem;
import com.apes.fn.scm.internal.help.repository.InternalHelpReturnApprovalRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.service.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.internal.help.service
 * @ClassName: PickFlowInternalHelpVoucherService
 * @Author: pyb
 * @CreateTime: 2020-06-13 11:19
 * @Description: 內协退货收货流转凭证
 * @Version: 1.0
 */
@Service("pickFlowInternalHelpVoucherService")
public class PickFlowInternalHelpVoucherService extends DomainService {

    @Autowired
    private InternalHelpReturnApprovalRepository internalHelpReturnApprovalRepository;

    /**
     * 內协退货 收货流转返厂凭证
     *
     * @param request Pick
     */
    public void pickFlowPurchaseReturnVoucher(SimpleRequest request) {
        Pick pick = request.getO(Pick.class);

        //获取內协退货单
        InternalHelpReturnApproval internalHelpReturnApproval = internalHelpReturnApprovalRepository.findOne(pick.getOrigin());
        Optional.ofNullable(internalHelpReturnApproval).orElseThrow(() -> new RuntimeException(String.format("內协退货单[%s]不存在!", pick.getOrigin())));

        // 获取合作伙伴(基地)
        PartyRole supplier = internalHelpReturnApproval.getReceiptLocation().getCompany().getParty().getPatyRoleByType("Supplier");
        //根据批次的合作方式 产生不同凭证
        internalHelpReturnApproval.getApprovalItems().stream()
                .collect(Collectors.groupingBy(item -> item.getInventoryBatch().getCooperation()))
                .forEach((cooperation, internalHelpReturnApprovalItems) -> {
                    //创建凭证
                    Voucher voucher = new Voucher();
                    voucher.setReturned(true);  // 退回标记
                    voucher.setCompany(internalHelpReturnApproval.getCompany());
                    voucher.setDept(internalHelpReturnApproval.getDept());
                    voucher.setClerk(internalHelpReturnApproval.getApplyUid());

                    voucher.setPartner(supplier);
                    voucher.setBusinessType(BusinessType.PURCHASE_RETURN);
                    voucher.setInventoryMode(cooperation.getInventoryMode());
                    voucher.setAccountingMethod(cooperation.getAccountingMethod());
                    voucher.setScene(internalHelpReturnApproval.getScene());
                    voucher.setOrigin(internalHelpReturnApproval.getId());
                    voucher.setOriginBusinessType(pick.getOriginBusinessType());
                    voucher.setSource(pick.getId());
                    voucher.setSourceBusinessType(pick.getInnerBusinessType());

                    // 从表信息
                    voucher.setVoucherItems(getPurchaseReturnVoucherItems(internalHelpReturnApproval, pick));
                    createVoucher(voucher);
                });
        // 回写內协退货单状态 (直接完成状态)
        internalHelpReturnApproval.setState("done");
        internalHelpReturnApprovalRepository.saveAndFlush(internalHelpReturnApproval);
    }

    /**
     * 获取明细接口
     *
     * @param internalHelpReturnApproval InternalHelpReturnApproval
     * @param pick Pick
     * @return Set<VoucherItem>
     */
    public Set<VoucherItem> getPurchaseReturnVoucherItems(InternalHelpReturnApproval internalHelpReturnApproval, Pick pick) {
        Set<VoucherItem> voucherItems = new HashSet();
        Map<String, InternalHelpReturnApprovalItem> itemMap = internalHelpReturnApproval.getApprovalItems().stream()
                .collect(Collectors.toMap(InternalHelpReturnApprovalItem::getId, item -> item));
        pick.getPickItems().forEach(
                pickItem -> {
                    VoucherItem voucherItem = new VoucherItem();
                    InternalHelpReturnApprovalItem item = itemMap.get(pickItem.getOriginLine());
                    if (item == null) {
                        throw new RuntimeException("未找到采购订单行：" + pickItem.getOriginLine());
                    }
                    voucherItem.setProduct(pickItem.getProduct());
                    voucherItem.setTax(item.getTax());
                    voucherItem.setOwner(internalHelpReturnApproval.getShipLocation().getCompany());
                    voucherItem.setUom(item.getUom());
                    // 回写发货数量
                    item.delivery(pickItem.getQtyDone());
                    voucherItem.setProductQty(-1.00 * item.getProductReturnQty());
                    voucherItem.setPriceUnit(item.getPriceUnit());
                    voucherItem.setOriginItemId(String.valueOf(item.getId()));
                    voucherItem.setSourceItemId(String.valueOf(pickItem.getId()));
                    voucherItem.setInventoryBatch(item.getInventoryBatch());
                    voucherItems.add(voucherItem);
                }
        );
        return voucherItems;
    }

    /**
     * 产生凭证接口
     *
     * @param voucher Voucher
     * @return Voucher
     */
    private Voucher createVoucher(Voucher voucher) {
        return invoke("voucher.create", MapUtil.mapped(voucher));
    }
}
